package loupan

import (
	"bytes"
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Http/Services/file/file_utils"
	"hft/e"
	"hft/global"
	"hft/tools"
	"hft/tools/upload"
	cus_utils "hft/tools/utils"
	"image/png"
	"net/url"
	"strconv"
	"strings"

	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/qr"
	"gorm.io/gorm"
)

type WhatsApp struct{}

// 设置whatsapp
func (*WhatsApp) SetApp(phone string, louID int) (err error) {
	var region *admin.Region
	var lou *admin.LouPan
	err = global.OC_DB.Select("id,name,whats_app_qr_code,region_link").First(&lou, louID).Error
	if err != nil {
		return errors.New(e.LouPanNotExist)
	}
	var strArr = strings.Split(lou.RegionLink, ",")
	var city, _ = strconv.Atoi(strArr[1 : len(strArr)-1][2])
	err = global.OC_DB.Select("id, pre_fix").Where("id = ?", city).First(&region).Error
	if err != nil {
		return errors.New(e.RegionNotFound)
	}
	if region.PreFix == "" {
		return errors.New(e.NoManagerHere)
	}
	err = global.OC_DB.Transaction(func(tx *gorm.DB) error {
		// 生成二维码
		word := fmt.Sprintf("我想咨询一下%v楼盘的信息:https://www.haofangtiao.com%s/loupan/detail/%v", lou.Name, region.PreFix, lou.ID)
		res, _ := cus_utils.LangBlock.Trans(word, "s2t")
		fmt.Println(phone, lou.Name)
		var str = fmt.Sprintf("https://wa.me/%s?text=%s", phone, url.QueryEscape(res))
		qrCode, _ := qr.Encode(str, qr.M, qr.Auto)
		qrCode, _ = barcode.Scale(qrCode, 256, 256)
		var bucket, _ = upload.NewBucket()
		var buf bytes.Buffer
		err := png.Encode(&buf, qrCode)
		var newFilename = file_utils.GenerateFIleName(fmt.Sprintf("%v%v.png", lou.Name, phone), tools.GenUUID())
		err = bucket.PutObject(newFilename, bytes.NewReader(buf.Bytes()))
		if err != nil {
			fmt.Println(err)
			return errors.New(e.QrCodeGenFail)
		}
		err = tx.Model(&admin.LouPan{}).Where("id = ?", louID).Updates(map[string]interface{}{
			"whats_app":         phone,
			"whats_app_qr_code": "/" + newFilename,
			"whats_word":        word,
		}).Error
		if err != nil {
			return errors.New(e.ErrorInfo)
		}
		if lou.WhatsAppQrCode != "" {
			err = upload.NewOss().DeleteFile([]string{lou.WhatsAppQrCode})
			if err != nil {
				return errors.New(e.DeleteFail)
			}
		}
		return err
	})

	return err
}

var WhatsAppService = new(WhatsApp)
